<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="月份" prop="month">
        <!-- 日期 -->
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          placeholder="请选择月份"
          value-format="YYYY-MM"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleExport"
          v-hasPermi="['system:contract:transactionType:add']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="dataList"
      :span-method="spanMethod"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="区域" align="center" prop="regionName" />
      <el-table-column
        label="店面"
        align="center"
        prop="storeName"
        width="150"
      />
      <el-table-column label="加盟商" align="center" prop="franchiseeName" />
      <el-table-column label="经纪人" align="center" prop="brokerName" />
      <el-table-column
        label="店面业绩"
        align="center"
        prop="storeIncomePrice"
      />
      <el-table-column
        label="公司业绩8%"
        align="center"
        prop="companyIncomePrice"
      />
      <el-table-column
        label="店面交易费"
        align="center"
        prop="companyTransactionFee"
      />
      <el-table-column label="套数" align="center" prop="numberOfSets" />
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleProcess(scope.row)"
            v-if="scope.row.isProcess == 0 || scope.row.isProcess == 2"
            v-hasPermi="['system:finishReg:submitCompletedReview']"
            >提交审核</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <div></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="addNewspaper">
import {
  addRefund,
  queryRefund,
  updateRefund,
  deleteRefund,
  submitAudit,
} from "@/api/business/refund";
import {
  listFinishReg,
  submitCompletedReview,
} from "@/api/dailyNewspaper/finishReg";
import { monthPaper } from "@/api/dailyNewspaper/addDetails";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
import { reactive } from "vue";
const dataList = ref([]);
const open = ref(false);
const openDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: 2,
    contractNo: "",
  },
  rules: {},
});

const { queryParams, rules } = toRefs(data);
const form = ref({});

//提交审核
function handleProcess(row) {
  const { id } = row;
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitCompletedReview({ id });
    })
    .then(() => {
      proxy.$modal.msgSuccess("提交成功");
      getList();
    });
}
/** 查询岗位列表 */
function getList() {
  loading.value = true;
  monthPaper(queryParams.value).then((response) => {
    const sortedData = sortDataForMerge(response.data, [
      "regionName",
      "storeName",
      "franchiseeName",
    ]);

    dataList.value = sortedData;

    total.value = response.total;
    loading.value = false;
  });
}
const mergeMap = computed(() => {
  return getHierarchicalMergeMap(dataList.value);
});
function sortDataForMerge(data, fields) {
  return [...data].sort((a, b) => {
    for (const field of fields) {
      if (a[field] !== b[field]) {
        return a[field] > b[field] ? 1 : -1;
      }
    }
    return 0;
  });
}
function spanMethod({ row, column, rowIndex }) {
  const prop = column.property;
  const map = mergeMap.value;

  if (map[prop] && map[prop][rowIndex] != null) {
    return [map[prop][rowIndex], 1];
  }

  for (const startRow in map[prop] || {}) {
    const span = map[prop][startRow];
    if (rowIndex > +startRow && rowIndex < +startRow + span) {
      return [0, 0];
    }
  }
}

function getHierarchicalMergeMap(
  data,
  fields = ["regionName", "storeName", "franchiseeName"]
) {
  const mergeMap = {};
  const rowCount = data.length;

  fields.forEach((field, level) => {
    mergeMap[field] = {};

    let startRow = 0;
    let spanCount = 1;

    for (let i = 1; i <= rowCount; i++) {
      const prev = data[i - 1];
      const curr = data[i];

      // 判断当前行是否和上一行在所有上级字段上相同
      const isSameGroup = fields
        .slice(0, level + 1)
        .every((f) => curr?.[f] === prev?.[f]);

      if (isSameGroup) {
        spanCount++;
      } else {
        if (spanCount > 1) {
          mergeMap[field][startRow] = spanCount;
        }
        startRow = i;
        spanCount = 1;
      }
    }
  });

  return mergeMap;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
function handleDetail(row) {
  queryRefund(row.id).then((response) => {
    form.value = response.data;
    openDetail.value = true;
  });
}
/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.id || ids.value;
  queryRefund(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改";
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除？")
    .then(function () {
      return deleteRefund(row.id);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
}
function handleSubmitAudit(row) {
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitAudit({ id: row.id });
    })
    .then(() => {
      proxy.$modal.msgSuccess("提交审核成功");
      getList();
    });
}
const refundAddRef = ref();
/** 提交按钮 */
function submitForm() {
  refundAddRef.value.validateForm().then((res) => {
    if (res) {
      if (refundAddRef.value.form.id) {
        updateRefund(refundAddRef.value.form).then((res) => {
          open.value = false;
          proxy.$modal.msgSuccess(res.msg);
          getList();
        });
      } else {
        // console.log(refundAddRef.value.form);
        addRefund(refundAddRef.value.form).then((res) => {
          open.value = false;
          proxy.$modal.msgSuccess(res.msg);
          getList();
        });
      }
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/system/saleDetails/export",
    {
      ...queryParams.value,
    },
    `addDetails_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
<style scoped></style>
